package protocol

import (
	"encoding/binary"
	"gitee.com/crack007/goose/core/server"
	"gitee.com/crack007/udp-penetrate/src/common/constant"
	"gitee.com/crack007/udp-penetrate/src/udpserver/service"
	"net"
)

type ConnectReqProtocol struct {
	TargetUid uint32
	OriginUid uint32
}

func NewConnectReqProtocol() *ConnectReqProtocol {
	return &ConnectReqProtocol{}
}

func (p *ConnectReqProtocol) Code() uint32 {
	return constant.CMD_CONNECT_REQ
}

// server端执行
func (p *ConnectReqProtocol) Process(session *server.Session, clientConn *net.UDPConn) IProtocol {
	targetSession := service.UserService.GetSessionByUid(p.TargetUid)
	originSession := service.UserService.GetSessionByUid(p.OriginUid)
	clientHandshakeReqProtocol := NewClientHandshakeReqProtocol()
	clientHandshakeReqProtocol.OriginHost = originSession.RemoteIp
	clientHandshakeReqProtocol.OriginPort = originSession.RemotePort
	clientHandshakeReqProtocol.TargetHost = targetSession.RemoteIp
	clientHandshakeReqProtocol.TargetPort = targetSession.RemotePort
	clientHandshakeReqProtocol.OriginUid = p.OriginUid
	packData, _ := PackData(clientHandshakeReqProtocol)
	targetSession.AsyncSend(packData)
	return nil
}

func (p *ConnectReqProtocol) Marshall() []byte {
	var body = make([]byte, 8)
	binary.BigEndian.PutUint32(body[:4], p.TargetUid)
	binary.BigEndian.PutUint32(body[4:], p.OriginUid)
	return body
}

func (p *ConnectReqProtocol) UnMarshall(data []byte) {
	p.TargetUid = binary.BigEndian.Uint32(data[:4])
	p.OriginUid = binary.BigEndian.Uint32(data[4:8])
}
